package com.example.springbooteasycode.zjrc.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerMain {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(8888)) {
            System.out.println("服务器已启动，监听端口 8888...");

            // 等待客户端连接（阻塞）
            try (Socket socket = serverSocket.accept()) {
                System.out.println("客户端已连接：" + socket.getInetAddress());

                // 接收客户端发送的数据
                InputStream is = socket.getInputStream();
                byte[] buffer = new byte[1024];
                int length = is.read(buffer);
                String receivedData = new String(buffer, 0, length);

                System.out.println("有效字节数: " + length);       // 输出 12
                System.out.println("有效数据: " + receivedData);   // 输出 Hello, World!
                System.out.println("数组总长度: " + buffer.length); // 输出 1024（预分配的长度）

                System.out.println("接收到的数据: " + receivedData);


                // 添加响应逻辑
                OutputStream os = socket.getOutputStream();
                String response = "服务器已收到: " + receivedData;
                os.write(response.getBytes());
                os.flush();
                System.out.println("已发送响应: " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
